﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using DataLayer.Entities;
using DataLayer.Implementations;
using DonutMgmtSystemFoundation.Models;
using ViewRes;

namespace DonutMgmtSystemFoundation.Helpers
{
    public class ProfileHelper
    {
        public GeneralJsonResultModel SaveUser(User user)
        {
            try
            {
                UserApplication app = new UserApplication();                
                User dbUser = SessionContext.GetUserData();
                 
                // Checar si existe por correo
                User duplicatedEmail = app.GetByEmail(user.Email);

                if (duplicatedEmail != null)
                {
                    if (duplicatedEmail.UserId != dbUser.UserId)
                    {
                        return new GeneralJsonResultModel(false, Profile.MsgErrorDupEmail);
                    }
                }

                User duplicatedUsername = app.GetByUsername(user.Username);

                if (duplicatedUsername != null)
                {
                    if (duplicatedUsername.UserId != dbUser.UserId)
                    {
                        return new GeneralJsonResultModel(false, Profile.MsgErrorDupUsername);
                    }
                }
                                
                dbUser.Username = user.Username;
                dbUser.Email = user.Email;

                app.Save(dbUser);
                return new GeneralJsonResultModel(true, Profile.MsgSavePrefsOk);
            }
            catch
            {
                return new GeneralJsonResultModel(false, Profile.MsgSavePrefsError);
            }
        }

        public GeneralJsonResultModel ResetPassword(string newPassword)
        {
            try
            {
                UserApplication userApp = new UserApplication();
                User currentUser = userApp.GetById(SessionContext.GetUserData().UserId.Value);

                currentUser.Password = EncryptionHelper.Encrypt(newPassword);

                userApp.Save(currentUser);

                return new GeneralJsonResultModel(true, Profile.SavePassOk);
            }
            catch
            {
                return new GeneralJsonResultModel(false, Profile.SavePassError);
            }
        }
    }
}